from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import gettext_lazy as _


class UserManager(BaseUserManager['User']):
    use_in_migrations = True

    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError("必须填写邮箱")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)

        if extra_fields.get("is_staff") is not True:
            raise ValueError("超级用户必须设置 is_staff=True")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("超级用户必须设置 is_superuser=True")

        return self.create_user(email, password, **extra_fields)


class User(AbstractUser):
    """
    自定义用户模型，替代Django自带的用户模型
    不包含组功能，只区分管理员和普通用户
    """

    # 重写USERNAME_FIELD，使用email作为登录字段
    USERNAME_FIELD = "email"

    # 重写REQUIRED_FIELDS，移除email字段和username字段
    REQUIRED_FIELDS = []

    email = models.EmailField(unique=True, verbose_name=_("Mail"))

    # 添加头像字段
    avatar = models.ImageField(upload_to="avatars/", blank=True, null=True, verbose_name=_("Avatar"))

    # 添加昵称字段
    nickname = models.CharField(max_length=50, blank=True, null=True, verbose_name=_("Nickname"))

    bio = models.TextField(verbose_name=_("Self Introduction"), null=True, blank=True)

    # 重写username字段，使其不再唯一且可以为空
    username = models.CharField(
        _("username"),
        max_length=150,
        blank=True,
        null=True,
        help_text=_("Optional username, not used for login."),
    )

    objects = UserManager()

    def __str__(self):
        return self.email

    # 修改is_staff字段，只允许超级用户访问后台
    is_staff = models.BooleanField(default=False, verbose_name=_("Able to access admin"))

    def has_perm(self, perm, obj=None):
        """判断用户是否有特定权限"""
        # 只有超级用户可以访问后台权限
        return self.is_superuser

    def has_module_perms(self, app_label):
        """判断用户是否有访问特定应用的权限"""
        # 只有超级用户可以访问应用模块
        return self.is_superuser

    def save(self, *args, **kwargs):
        """重写save方法，确保is_staff与is_superuser保持一致"""
        # 确保只有超级用户才能访问后台
        self.is_staff = self.is_superuser

        # 如果username为空，则设置为None
        if not self.username:
            self.username = None
        super().save(*args, **kwargs)
